<?php
namespace Game\Entity;

use Game\Action\Character\PunchAction;
use Game\Entity\Character;
use Symfony\Component\HttpFoundation\Request;
use Game\Exception\Environment\EnvironmentException;
use Game\Factory\ActionFactory;

/**
 * @Entity
 */
class BattleEnvironment extends Environment
{

    protected function _getActions()
    {
        return array('punch');
    }

    public function executeCommand(Character $character, Request $request)
    {
        $result = array();

        parent::executeCommand($character, $request);

        $command = $request->get('command');

        $enemies = $this->getOtherCharacters($character);

        if( $enemies->isEmpty() )
            throw new EnvironmentException(sprintf('Enemies not found in battle environment %d for character %d',
                    $this->getId(),
                    $character->getId()
                    ));

//        if( $enemies->count() > 1 )
//        {
//            $target = $request->get('target');
//        }

        $enemy = $enemies->first();
        $action = $character->getAction($command);
        if( !$action )
            throw new EnvironmentException(sprintf('Action "%s" not found in battle environment %d for character %d',
                    $command,
                    $this->getId(),
                    $character->getId()
                    ));

        $em = \App\Globals::init()->getEntityManager();

        $action->execute($enemy);
        $em->persist($enemy);
        $result['person'] = $action->getResultArray();
        $result['enemies'] = array();
        $all_enemies_are_dead = true;
        foreach($enemies as $enemy)
        {
            $enemy instanceof Character;
            if( $enemy->isDead() ) continue;
            $all_enemies_are_dead = false;
            $enemy->addAction($action);
            $action->execute($character);
            $result['enemies'][$enemy->getId()] = $action->getResult();
            if( $character->isDead() ) break;
        }
        $em->persist($character);
        $em->flush();

        $result['enemies_dead'] = $all_enemies_are_dead;
        return $result;
    }
}